<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>角色-权限关系编辑</title>
    <link href="common/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="common/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="common/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="common/js/new_common.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">后台演示 </a>
        </div>
        <div>
            <ul class="nav navbar-nav">
                <li><a href="./webSocket.html">webSocket测试</a></li>
                <li><a href="./editRole.html">角色</a></li>
                <li><a href="./editAdminRole.html">管理员-角色关系</a></li>
                <li><a href="./editAccess.html">权限</a></li>
                <li><a href="./editRoleAccess.html">角色-权限关系</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        管理员 <b class="caret"></b>
                    </a>
                    <ul class="dropdown-menu">
                        <li><a href="./admininfo.html">用户信息</a></li>
                        <li><a href="./logout.html">退出登录</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>




<table class="table table-striped">
    <caption>角色列表</caption>
    <thead>
    <tr>
        <th>角色名称</th>
        <th>权限列表</th>
        <th>创建时间</th>
        <th>更新时间</th>
        <th>更改该角色</th>
        <th>删除该角色</th>
    </tr>
    </thead>
    <tbody id="list">

    </tbody>
</table>

<div>
    选择当前操作角色：
    <div class="btn-group">
        <button type="button" class="btn btn-primary dropdown-toggle" id="roleBtn" data-toggle="dropdown">选择角色
            <span class="caret"></span>
        </button>
        <ul class="dropdown-menu" role="menu" id="roleName"></ul>
    </div>
</div>

<div style="width: 100%;height: 2px;background:grey;margin: 2rem 0;"></div>
<label for="roleCheckBox">为当前角色选择权限</label>
<button class="btn btn-success" id="add">添加</button>
<div id="roleCheckBox">
    <!--
    <label class="checkbox-inline">
        <input type="checkbox" id="inlineCheckbox3" value="option3" checked> 选项 3
    </label>
    -->
</div>


<script>

    var roleList,accessList,currenRoleId,currenRoleName,type,addAccessIdList='';

    $(document).ready(function () {
        var url = '../api/rbac/showRoleList';
        var strJson = {'random':Math.random()};
        nameList(url,strJson); // 初始化权限的值
        showAccessList();
        addSubmit();
    });

    /**
     * 展示所有权限列表
     */
    function showAccessList() {
        type = 'list';
        var jsonStr = {'random':Math.random()};
        var sUrl = '../api/rbac/listAccess';
        ajaxSubmit(sUrl,jsonStr);
    }

    /**
     * 展示角色列表
     * @param url
     * @param strJson
     */
    function nameList(url,strJson){
        $.ajax({
            url:url,
            type:'post',
            timeout:6000,
            async:true,
            beforeSend:function (XMLHttpRequest) {},
            cache:false,
            complete:function (XMLHttpRequest, textStatus) {},
            contentType:'application/x-www-form-urlencoded',
            data:strJson,
            dataType:'json',
            error:function (XMLHttpRequest, textStatus, errorThrow) {},
            global:true,
            ifModified:false,
            processData:true,
            success:function (result, textStatus) {
                roleList = result.data;

                showSelect($('#roleName')); // 展示权限列表（select）
                listLiClick(); // 监听权限列表 ul li

            }

        });
    }

    /**
     * 展示角色下拉框
     */
    function showSelect(roleNameObj) {
        var roleLength = roleList.length;

        if (roleNameObj) {
            var roleArr = [];
            for (var i = 0; i < roleLength; i++) {
                var roleHtml =
                    '<li>' +
                    '<a href="#">' + roleList[i].name + '</a>' +
                    '<span style="display: none;">' + roleList[i].id + '</span>' +
                    '</li>';
                roleArr.push(roleHtml);
            }
            roleNameObj.append(roleArr.join(''));
        }

    }

    /**
     * 点击角色
     */
    function listLiClick() {
        $('#roleName li a').bind('click',function () {
            currenRoleName = $(this).text();
            $('#roleBtn').text(currenRoleName);
            currenRoleId = $(this).next().text();
            // 点击角色，根据角色role_id去角色-权限表查询对应权限列表
            type = 'find';
            var strJson = {'role_id':currenRoleId};
            addAccessIdList = ''; // 重新初始化addAccessIdList
            var sUrl = '../api/rbac/findRoleAccess';
            ajaxSubmit(sUrl,strJson);

        });
    }

    /**
     * 将所有获取的 access_id 拼装
     * @param id
     */
    function addList(id) {
        if(!checkEmptyValue(addAccessIdList)){
            addAccessIdList = addAccessIdList + ',' + id;
        }else {
            addAccessIdList = id;
        }
    }

    /**
     * 给角色添加权限
     */
    function addSubmit() {
        $('#add').bind('click',function () {
            type = 'add';
            var strJson = {'access_id_list':addAccessIdList,'role_id':currenRoleId};
            var sUrl = '../api/rbac/addRoleAccess';
            ajaxSubmit(sUrl,strJson);
        });
    }

    /**
     * 删除一条对应关系记录
     * 这个id是表 admin_role 的自动增长id
     */
    function deleteOne(id) {
        type = 'delete';
        var strJson = {'type':type,'id':id};
        var sUrl = '../api/rbac/deleteRoleAccess';
        ajaxSubmit(sUrl,strJson);
    }

    // todo 将id和获取access_id_list传递到后台即可
    function updateOne(id, name) {
        // ../api/rbac/updateRoleAccess/
        console.dir('id:'+id+'    name:'+name);
    }

    function ajaxSubmit(sUrl,strJson){
        $.ajax({
            url:sUrl,
            type:'post',
            timeout:6000,
            async:true,
            beforeSend:function (XMLHttpRequest) {},
            cache:false,
            complete:function (XMLHttpRequest, textStatus) {},
            contentType:'application/x-www-form-urlencoded',
            data:strJson,
            dataType:'json',
            error:function (XMLHttpRequest, textStatus, errorThrow) {},
            global:true,
            ifModified:false,
            processData:true,
            success:function (result, textStatus) {
                var status = result.result === 'success';
                switch (type) {
                    case 'list': // 获取权限列表
                        accessList = result.data;
                        var listLength = accessList.length;
                        var roleArr = [];
                        for(var i=0;i<listLength;i++){
                            var roleHtml =
                                '   <label class="checkbox-inline">\n' +
                                '        <input type="checkbox" name=id"'+accessList[i].id+'"' +
                                '        value="'+accessList[i].id+'" onclick="addList(\''+accessList[i].id+'\');">\n' +accessList[i].title +
                                '    </label>';
                            roleArr.push(roleHtml);
                        }
                        $('#roleCheckBox').empty();
                        $('#roleCheckBox').append(roleArr.join(''));
                        break;
                    case 'find':
                        if(result.data){
                            var roleAccessList = result.data;
                            var accessIdList = roleAccessList.access_id;
                           // 获取角色对应权限access_id列表后，将权限access_id列表展示为权限名列表

                            if(!checkEmptyValue(accessIdList)){
                                var accessIdArr = accessIdList.split(',');
                                var accessListLength = accessList.length;
                                var accessNameList='';

                                for(var j=0;j<accessListLength;j++){
                                    if($.inArray(accessList[j]['id'].toString(),accessIdArr) !== -1){

                                        if(accessNameList !== ''){
                                            accessNameList = accessNameList + ' | ' + accessList[j]['title'];
                                        }else {
                                            accessNameList = accessList[j]['title'];
                                        }

                                    }
                                }

                                var currentAccessHtml =
                                    ' <tr>\n' +
                                    '        <td>'+currenRoleName+'</td>\n' +
                                    '        <td>'+accessNameList+'</td>\n' +
                                    '        <td>'+roleAccessList.create_time+'</td>\n' +
                                    '        <td>'+roleAccessList.update_time+'</td>\n' +
                                    '        <td style="color: green;" onclick="updateOne(\''+roleAccessList.id+'\',\''+currenRoleName+'\')">更改</td>\n' +
                                    '        <td style="color: red;" onclick="deleteOne(\''+roleAccessList.id+'\')">删除</td>\n' +
                                    '    </tr>';

                                $('#list').empty();
                                $('#list').append(currentAccessHtml);
                            }


                        }
                        break;
                    case 'add':
                    case 'update':
                    case 'delete':
                        if (status)
                            window.location.reload();
                        break;
                }
            }

        });
    }

    // 10000 一年 （30年10年） 15800，
    // 100000 - 158000
    // 意外保险，乘客双倍、节假日3倍
    // 10000 一年 600-800 利息    66*12

</script>

</body>
</html>
